#include "tcpsocket.h"
#include <QDebug>
#include <QThread>
#include "connector.h"
#include "connectorlist.h"

TcpSocket::TcpSocket() {}

void TcpSocket::send()
{
//     //连接到服务端，以异步的方式连接，连接成功之后会发射connected信号
//     socket.connectToHost("127.0.0.1",6002);
//     //等待连接，默认等待30s
//     bool res = socket.waitForConnected();
//     if(res)
//     {
//         //连接成功
//         qDebug() << "connected success";
//     }
//     connect(&socket,SIGNAL(connected()),this,SLOT(clientConnected()));
}

void TcpSocket::server()
{
    m_server = new QTcpServer(this);
    //1.监听
    //2.当有新的连接时，触发newConnection信号
    connect(m_server,SIGNAL(newConnection()),this,SLOT(acceptConnect()));
    if(m_server->listen(QHostAddress::LocalHost,6003))
    {
        qDebug() << "listen success";
    }else {
        qDebug() << "listen error";
    }
}

void TcpSocket::stopListen()
{
    if(m_server->isListening())
    {
        m_server->close();
    }
}

void TcpSocket::acceptConnect()
{

    //3.返回下一个等待接入的连接
    QTcpSocket* socket = m_server->nextPendingConnection();

    //4.打印对方信息，socket->peerAddress();返回对方的socket地址
    qDebug() << "new connection : " << socket->peerAddress().toString();
    //5.有数据到来触发readyRead信号
    QThread* thread = new QThread();
    Connector* connector = new Connector(socket,thread);
    connect(socket,SIGNAL(readyRead()),connector,SLOT(readData()));
    connect(socket,SIGNAL(disconnected()),connector,SLOT(disconnected));
    connect(thread,&QThread::finished,[&]{
        qDebug() << "thread is over";
    });

    connect(thread,&QThread::finished,&QThread::deleteLater);
    connect(socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),connector,SLOT(stateChanged(QAbstractSocket::SocketState)));
    ConnectorList::getClients()->insert(connector->m_socketName,connector);
    qDebug() << ConnectorList::getClients()->size();
    //QObject::moveToThread: Cannot move objects with a parent
    connector->moveToThread(thread);
    thread->start();
}

void TcpSocket::clientConnected()
{
    // qDebug() << "connected";
    // char msg[] = "hello 我来了";
    // socket.write(msg);
    // socket.flush();
}

void TcpSocket::do_connected()
{
    qDebug() << "do_connected";
}
